// 金融格式 ，分割和两位小数
export function rounding(value) {
  if (value != undefined) {
    if (value && value != null) {
      value = String(value);
      let left = value.split('.')[0], right = value.split('.')[1];
      right = right ? (right.length >= 2 ? '.' + right.substr(0, 2) : '.' + right + '0') : '.00';
      let temp = left.split('').reverse().join('').match(/(\d{1,3})/g);
      return (Number(value) < 0 ? "-" : "") + temp.join(',').split('').reverse().join('') + right;
    } else if (value === 0) {   //注意===在这里的使用，如果传入的value为0,if中会将其判定为boolean类型，故而要另外做===判断
      return '0.00';
    } else {
      return "";
    }
  }
  return "";
}

// 金融格式 整数
export function formatNum(value) {
  if (value != undefined) {
    if (value && value != null) {
      value = String(value);
      let left = value.split('.')[0], right = value.split('.')[1];
      //right = right ? (right.length>=2 ? '.'+right.substr(0,2) : '.'+right+'0') : '.00';
      let temp = left.split('').reverse().join('').match(/(\d{1,3})/g);
      return (Number(value) < 0 ? "-" : "") + temp.join(',').split('').reverse().join('')//+right;
    } else if (value === 0) {   //注意===在这里的使用，如果传入的value为0,if中会将其判定为boolean类型，故而要另外做===判断
      return '0';
    } else {
      return "";
    }
  }
  return "";
}

// 金融格式 小数
export function formatDot(value) {
  if (value != undefined) {
    if (value && value != null) {
      //四舍五入两位小位
      value = parseFloat(value).toFixed(2);
      value = String(value);
      let right = value.split('.')[1];
      return '.' + String(right);
    } else if (value === 0) {
      return '.00';
    } else {
      return ".00";
    }
  }
  return "";
}

// 金融格式去掉逗号
export function formatComma(value) {
  if (value != undefined) {
    if (value && value != null) {
      //四舍五入两位小位
      value = value.replace(/,/g, '');
      return value;
    } else {
      return "0";
    }
  }
  return "0";
}

export function upAmount(number) {
  var ret = "";
  if (number != "" && number != null && number != "0") {
    var unit = "仟佰拾亿仟佰拾万仟佰拾元角分",
      str = "";
    number += "00";
    var point = number.indexOf(".");
    if (point >= 0) {
      number = number.substring(0, point) + number.substr(point + 1, 2);
    }
    unit = unit.substr(unit.length - number.length);
    for (var i = 0; i < number.length; i++) {
      str +=
        "零壹贰叁肆伍陆柒捌玖".charAt(number.charAt(i)) + unit.charAt(i);
    }
    ret =
      str
        .replace(/零(仟|佰|拾|角)/g, "零")
        .replace(/(零)+/g, "零")
        .replace(/零(万|亿|元)/g, "$1")
        .replace(/(亿)万|(拾)/g, "$1$2")
        .replace(/^元零?|零分/g, "")
        .replace(/元$/g, "元") + "整";
  }
  return ret;
}

// 日期格式化
export function formatDate(time, fmt) {
  if (time == null || time == "") { return "" };
  var date = parseToDate(time);
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  var o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      var str = o[k] + ''
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : ('00' + str).substr(str.length))
    }
  }
  return fmt;
}

function parseToDate(value) {
  if (value == null || value == '') {
    return undefined;
  }
  var dt;
  if (value instanceof Date) {
    dt = value;
  }
  else {
    if (!isNaN(value)) {
      dt = new Date(value);
    }
    else if (value.indexOf('/Date') > -1) {
      value = value.replace(/\/Date(−?\d+)\//, '$1');
      dt = new Date();
      dt.setTime(value);
    } else if (value.indexOf('/') > -1) {
      dt = new Date(Date.parse(value.replace(/-/g, '/')));
    } else {
      // 兼容ie11(只认准yyyy/MM/格式)
      if (value.toString().indexOf("-") > 0) {
        value = value.replace(new RegExp("-", "g"), "/");
      }
      dt = new Date(value);
    }
  }
  return dt;
}

/*
 *文件下载
 * 调用
 * downs(){
 * this.downloadIamge(this.pic.url, 'pic')
 *}
 */
export function downloadIamge(imgsrc, name) {//下载图片地址和图片名
  var image = new Image();
  // 解决跨域 Canvas 污染问题
  image.setAttribute("crossOrigin", "anonymous");
  image.onload = function () {
    var canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;
    var context = canvas.getContext("2d");
    context.drawImage(image, 0, 0, image.width, image.height);
    var url = canvas.toDataURL("image/png"); //得到图片的base64编码数据

    var a = document.createElement("a"); // 生成一个a元素
    var event = new MouseEvent("click"); // 创建一个单击事件
    a.download = name || "photo"; // 设置图片名称
    a.href = url; // 将生成的URL设置为a.href属性
    a.dispatchEvent(event); // 触发a的单击事件
  };
  image.src = imgsrc;
}
/**
 * 通用字典过滤器
 * **/
export function filterCredDict(val, type, dict) {
  if ((!val && val != '0') || !type || !dict) return ''
  const arr = dict[type]
  if (!arr) return val
  let temp = {}
  arr.forEach(item => {
    if (item.CODE == val || item.code == val || item.dictValue == val) {
      temp = item
    }
  })
  if (temp.dictLabel) {
    return temp.dictLabel
  } else if (temp.FLAG) {
    return temp.FLAG
  } else if (temp.flag) {
    return temp.flag
  } else if (temp.mark) {
    return temp.mark
  } else if (temp.MARK) {
    return temp.MARK
  } else {
    return val
  }
}

export function formatterEmpty(v, type = '0') {
  if (!v) return typev
  return v
}

/**
 * 电话号码中间4位隐藏
 * **/
export function hiddenPhoneNum(num) {
  if (num) {
    return num.replace(/^(.{3})(?:\d+)(.{4})$/, "$1******$2")
  } else {
    return num
  }
}

/**
 * 票据状态对应样式
 * **/
export function formatStatus(v) {
  // .state-blue,.state-green,.state-orange,.state-red,.state-yellow,.state-crimson,.state-gray
  let c = ''
  const n = v.toString()
  switch (n) {
    case '10':
      c = 'state-blue'
      break;
    case '15':
      c = 'state-red'
      break;
    case '20':
      c = 'state-yellow'
      break;
    case '25':
      c = 'state-crimson'
      break;
    case '30':
      c = 'state-gray'
      break;
    case '35':
      c = 'state-red'
      break;
    case '40':
      c = 'state-crimson'
      break;
    case '45':
      c = 'state-red'
      break;
    case '50':
      c = 'state-crimson'
      break;
    case '60':
      c = 'state-crimson'
      break;
    case '65':
      c = 'state-red'
      break;
    case '70':
      c = 'state-yellow'
      break;
    case '80':
      c = 'state-green'
      break;
    case '85':
      c = 'state-red'
      break;
    case '90':
      c = 'state-red'
      break;
  }
  return c
}

/**
 * 区间处理
 * **/
export function formatNo(val) {
  if (!val) return val
  /*return (Array(10).join("0") + val).slice(-10);*/
  //区间需要补齐12位
  return (Array(12).join("0") + val).slice(-12);
}
